package com.zx.config;/**
 * Author:JasonZ
 * Data:2023/4/20
 */

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @program: ecommerce-parent
 *
 * @description: 自定义异步线程池
 *
 * @author: JasonZ
 *
 * @create: 2023-04-20 16:30
 **/
@Configuration
@Slf4j
@EnableAsync // 启用异步任务支持
public class AsyncPoolConfig implements AsyncConfigurer {

    @Bean
    @Override
    public Executor getAsyncExecutor() {
        //配置线程池
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置线程池参数
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setKeepAliveSeconds(60);
        executor.setQueueCapacity(20);
        executor.setThreadNamePrefix("Jason-");

        //设置等待任务完成之后关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //设置等待时间
        executor.setAwaitTerminationSeconds(60);

        //设置拒绝策略
        executor.setRejectedExecutionHandler(
                //交给用户线程解决
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        //线程池初始化
        executor.initialize();
        return executor;
    }
}
